package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @Reference
    MemberService memberService;

    /**
     * {
     *    flag: true ,
     *    message: '会员数量统计成功！',
     *    data: {
     *          months: ['2020-01','2020-02'],
     *          memberCount:[10, 20]
     *     }
     * }
     *
     *
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        Map<String,Object> map = memberService.getMemberReport();
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map );
    }

    @Reference
    private SetmealService setmealService;
    /**
     * 套餐占比统计
     * @return
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        log.debug("ReportController: getSetmealReport ");
        // 获取套餐占比数据
        List<Map<String,Object>> setmealCountList = setmealService.findSetmealCount();
        // 获取套餐名称
        List<String> setmealNames = new ArrayList<>();
        for (Map<String,Object> mapSetmeal:setmealCountList){
            String setmealName = (String)mapSetmeal.get("name");
            setmealNames.add(setmealName);
        }
        // 构建返回数据
        Map<String,Object> mapData = new HashMap<>();
        mapData.put("setmealCount",setmealCountList);
        mapData.put("setmealNames",setmealNames);
        log.debug("套餐预约占比统计成功！");
        log.debug(mapData.toString());
        return new Result(true,MessageConst.ACTION_SUCCESS,mapData);
    }

    @Reference
    private ReportService reportService;

    /**
     * 获取运营统计数据
     * @return
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        Map<String,Object> result = reportService.getBussinessReport();
        System.out.println("result:"+result);
        return new Result(true,MessageConst.ACTION_SUCCESS, result );
    }

    /**
     *  @Author ZhangYi
     *  @Description //TODO 根据性别和年龄统计会员的分布(未优化)
     *  @Date  3:49 2020/3/8
     *  @Param []
     *  @return com.itheima.entity.Result
     */
//    @RequestMapping("/getMemberMessage1")
//    public Result getMemberMessage1(){
////        1.日志输出
//        log.debug("RequestController:getMemberMessage");
////        2.调用业务层
//        Map<String, Object> resultMap = memberService.getMemberMessage();
//        log.debug("ResultOfGetMemberMessage"+resultMap);
//        System.out.println("ResultOfGetMemberMessage"+resultMap);
//        return new Result(true,MessageConst.ACTION_SUCCESS,resultMap);
//    }

/**
 *  @Author ZhangYi
 *  @Description //TODO 根据性别和年龄统计会员的分布(调用业务层,响应web页面)
 *  @Date  3:58 2020/3/9
 *  @Param []
 *  @return com.itheima.entity.Result
 */
    @RequestMapping("/getMemberMessage")
    public Result getMemberMessage(){
        try {
//        1.日志记录
            log.debug("RequestController:getMemberMessage");
//        2.调用业务层
//                2.1 获取会员年龄分布信息
            List<Map<String, String>> memberCountByAge = memberService.getMemberCountByAge();
            log.debug("memberCountByAge::"+memberCountByAge);
//                2.2 获取会员性别分布信息
            List<Map<String, String>> memberCountBySex = memberService.getMemberCountBySex();
            log.debug("memberCountBySex::"+memberCountBySex);
//        3.封装结果集
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("age",memberCountByAge);
            resultMap.put("sex",memberCountBySex);
            log.debug("ResultOfGetMemberMessage::"+resultMap);
//          4.  返回结果集
            return new Result(true,MessageConst.GET_MEMBER_DISTRIBUTION_INFORMATION_SUCCESS,resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_MEMBER_DISTRIBUTION_INFORMATION_FAIL);
        }
    }

/**
 *  @Author ZhangYi
 *  @Description //TODO 选择日期范围现实折线图
 *  @Date  7:00 2020/3/10
 *  @Param [valueDate]
 *  @return com.itheima.entity.Result
 */
    @RequestMapping("/getReportByDate")
    public Result getReportByDate(@RequestBody String[] valueDate) throws ParseException {
        try {
            log.debug("getReportByDate::"+valueDate);
           List<String> stringDate  = valueDateToyyyyMM(valueDate);
            String starDate = stringDate.get(0);
            String endDate = stringDate.get(1);
            log.debug("stringDate::"+stringDate);
//        调用业务层,获取结果集
            Map<String, Object> resultMap = memberService.getReportByDate(starDate, endDate);
            log.debug("result:::"+resultMap);
            return new Result(true,MessageConst.ACTION_SUCCESS,resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }

//    将数据装换为yyyy-MM字符串
    private List<String> valueDateToyyyyMM(String[] valueDate) {
        String starDate=valueDate[0];
        String endDate=valueDate[1];
//        切割字符串 存入数组 [yyyy,MM]
        String[] starDate0 = starDate.split("-");
        String[] endDate0 = endDate.split("-");
//        拼接字符串
        starDate = starDate0[0] + "-" + starDate0[1];
        endDate = endDate0[0]+"-"+endDate0[1];
//        日志信息记录
        log.debug("开始时间:"+starDate);
        log.debug("结束时间:"+endDate);
//        将转换的数值存入List集合并返回
        List<String> stringDate = new ArrayList<>();
        stringDate.add(starDate);
        stringDate.add(endDate);
        return stringDate;
    }

    /**
     * 导出运营数据到本地
     *      步骤
     *          1. 创建模板
     *          2. 获取运营统计数据
     *          3. 把运营数据写入到excel
     *          4. 下载excel到本地
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response){
        try {
            //2. 获取运营统计数据
            Map<String, Object> businessReportData = reportService.getBussinessReport();
            //获取统计日期
            Object reportDate = businessReportData.get("reportDate");
            Object totalMember = businessReportData.get("totalMember");
            Object todayNewMember = businessReportData.get("todayNewMember");
            Object thisWeekNewMember = businessReportData.get("thisWeekNewMember");
            Object thisMonthNewMember = businessReportData.get("thisMonthNewMember");
            Object todayOrderNumber = businessReportData.get("todayOrderNumber");
            Object todayVisitsNumber = businessReportData.get("todayVisitsNumber");
            Object thisWeekOrderNumber = businessReportData.get("thisWeekOrderNumber");
            Object thisWeekVisitsNumber = businessReportData.get("thisWeekVisitsNumber");
            Object thisMonthOrderNumber = businessReportData.get("thisMonthOrderNumber");
            Object thisMonthVisitsNumber = businessReportData.get("thisMonthVisitsNumber");
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) businessReportData.get("hotSetmeal");

            //3. 把运营数据写入到excel
            //获取excel的输入流对象
            InputStream inputStream = this.getClass().getResourceAsStream("/template/report_template.xlsx");
            //创建工作薄对象
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            //获取工作表对象（sheet）
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            //设置统计日期
            //获取行对象
            Row row = sheet.getRow(2);
            //获取单元格
            Cell cell = row.getCell(5);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(reportDate));

            //设置今日新增会员数
            //获取行对象
            row = sheet.getRow(4);
            //获取单元格
            cell = row.getCell(5);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(todayNewMember));


            //设置总会员数
            //获取行对象
            row = sheet.getRow(4);
            //获取单元格
            cell = row.getCell(7);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(totalMember));


            //设置本周新增会员数
            //获取行对象
            row = sheet.getRow(5);
            //获取单元格
            cell = row.getCell(5);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(thisWeekNewMember));

            //设置本月新增会员数
            //获取行对象
            row = sheet.getRow(5);
            //获取单元格
            cell = row.getCell(7);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(thisMonthNewMember));


            //设置今日预约数
            //获取行对象
            row = sheet.getRow(7);
            //获取单元格
            cell = row.getCell(5);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(todayOrderNumber));

            //设置今日到诊数
            //获取行对象
            row = sheet.getRow(7);
            //获取单元格
            cell = row.getCell(7);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(todayVisitsNumber));


            //设置本周预约数
            //获取行对象
            row = sheet.getRow(8);
            //获取单元格
            cell = row.getCell(5);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(thisWeekOrderNumber));

            //设置本周到诊数
            //获取行对象
            row = sheet.getRow(8);
            //获取单元格
            cell = row.getCell(7);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(thisWeekVisitsNumber));


            //设置本月预约数
            //获取行对象
            row = sheet.getRow(9);
            //获取单元格
            cell = row.getCell(5);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(thisMonthOrderNumber));

            //设置本月到诊数
            //获取行对象
            row = sheet.getRow(9);
            //获取单元格
            cell = row.getCell(7);
            //设置单元格的数据
            cell.setCellValue(String.valueOf(thisMonthVisitsNumber));

            //声明行号
            int rownum = 12;
            for (Map<String, Object> map : hotSetmeal) {
                //获取行对象
                row = sheet.getRow(rownum);
                //
                cell = row.getCell(4);
                cell.setCellValue(String.valueOf(map.get("name")));
                //获取行，给行赋值
                cell = row.getCell(5);
                cell.setCellValue(String.valueOf(map.get("setmeal_count")));
                //获取行，给行赋值
                cell = row.getCell(6);
                cell.setCellValue(String.valueOf(map.get("proportion")));

                rownum ++ ;
            }

            //4. 下载excel到本地
            // 通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            //指定附件的格式为excel
            response.setContentType("application/vnd.ms-excel");
            //attachment 以附件下载
            //下载弹出框架中的默认的文件名
            response.setHeader("content-Disposition","attachment;filename="+reportDate+"_report.xlsx");
            //输出流下载
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}